package com.zky.gulimall.seckill.service.impl;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.zky.common.to.mq.SecKillOrderTo;
import com.zky.common.utils.R;
import com.zky.common.vo.MemberRespVo;
import com.zky.gulimall.seckill.feign.CouponFeignService;
import com.zky.gulimall.seckill.feign.ProductFeignService;
import com.zky.gulimall.seckill.interceptor.UserLoginInterceptor;
import com.zky.gulimall.seckill.service.SecKillService;
import com.zky.gulimall.seckill.to.SecKillSkuRedisTo;
import com.zky.gulimall.seckill.vo.SecKillSessionWithSkus;
import com.zky.gulimall.seckill.vo.SecKillSkuVo;
import com.zky.gulimall.seckill.vo.SkuInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @Description 秒杀
 * @Author 张开源
 * @Date 2022/12/26 13:19
 * @Version 1.0
 **/
@Service
@Slf4j
public class SecKillServiceImpl implements SecKillService {
    @Autowired
    private CouponFeignService feignService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private ProductFeignService productFeignService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private RedissonClient redissonClient;

    private static final String SESSION_CACHE_PREFIX = "secKill:sessions:";
    private static final String SKUKILL_CACHE_PREFIX = "secKill:skus:";
    private static final String SKU_STOCK_SEMAPHORE_PREFIX = "secKill:stock:";

    @Override
    public void uploadSecKillSkuLatest3Days() {
        //扫描最近三天需要参与秒杀的活动
        R last3DaySession = feignService.getLast3DaySession();
        if (!last3DaySession.isSuccess()) {
            log.error("uploadSecKillSkuLatest3Days return fail ,msg:{}", last3DaySession.getMsg());
            return;
        }
        String data = JSON.toJSONString(last3DaySession.get("data"));
        List<SecKillSessionWithSkus> withSkuses = JSON.parseObject(data, new TypeReference<List<SecKillSessionWithSkus>>() {
        });
        if (CollectionUtils.isEmpty(withSkuses)) {
            log.warn("uploadSecKillSkuLatest3Days  getLast3DaySession return empty");
            return;
        }
        //商品上架redis
        log.warn("uploadSecKillSkuLatest3Days  getLast3DaySession result:{}", JSON.toJSONString(withSkuses));
        //缓存活动信息
        saveSessionInfos(withSkuses);
        //缓存活动商品信息
        saveSessionSkuInfos(withSkuses);

    }

    @SentinelResource(value = "getCurrentSecKillSkusResource", blockHandler = "blockHandler")
    @Override
    public List<SecKillSkuRedisTo> getCurrentSecKillSkus() {
        try (Entry entry = SphU.entry("secKillSkus")) {
            //确定当前时间属于哪个场次
            Set<String> keys = redisTemplate.keys(SESSION_CACHE_PREFIX + "*");
            if (CollectionUtils.isEmpty(keys)) {
                return null;
            }
            long time = new Date().getTime();
            for (String key : keys) {
                String replace = key.replace(SESSION_CACHE_PREFIX, "");
                String[] split = replace.split("_");
                Long startTime = Long.parseLong(split[0]);
                Long endTime = Long.parseLong(split[1]);
                if (time >= startTime && time <= endTime) {
                    //获取这个秒杀场次需要的所有商品信息
                    List<String> range = redisTemplate.opsForList().range(key, -100, 100);
                    if (!CollectionUtils.isEmpty(range)) {
                        BoundHashOperations<String, String, Object> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
                        List<Object> multiGet = hashOps.multiGet(range);
                        if (!CollectionUtils.isEmpty(multiGet)) {
                            List<SecKillSkuRedisTo> skuRedisTos = multiGet.stream().map(item -> {
                                SecKillSkuRedisTo skuRedisTo = JSON.parseObject(String.valueOf(item), SecKillSkuRedisTo.class);
                                //预告里不能透出随机码
                                //skuRedisTo.setRandomCode(null);
                                return skuRedisTo;
                            }).collect(Collectors.toList());
                            return skuRedisTos;
                        }
                    }
                    break;
                }
            }
        } catch (BlockException e) {
            log.error("secKillSkus 被限流,msg:{}", e.getMessage());
        }
        return null;
    }

    public List<SecKillSkuRedisTo> blockHandler(BlockException exception) {
        log.error("getCurrentSecKillSkus 流控降级,msg:{}", exception.getMessage());
        return null;
    }

    @Override
    public SecKillSkuRedisTo getSkuSecKillInfo(Long skuId) {
        //找到所有参与秒杀的商品key
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        Set<String> keys = hashOps.keys();
        if (!CollectionUtils.isEmpty(keys)) {
            String reg = "\\d_" + skuId;
            for (String key : keys) {
                if (Pattern.matches(reg, key)) {
                    String json = hashOps.get(key);
                    SecKillSkuRedisTo redisTo = JSON.parseObject(json, SecKillSkuRedisTo.class);
                    long startTime = redisTo.getStartTime();
                    long endTime = redisTo.getEndTime();
                    long currentTime = new Date().getTime();
                    if (!(currentTime >= startTime && currentTime <= endTime)) {
                        redisTo.setRandomCode(null);
                    }
                    return redisTo;
                }
            }
        }
        return null;
    }

    @SentinelResource("kill")
    @Override
    public String kill(String killId, String key, Integer num) {

        long s1 = System.currentTimeMillis();
        MemberRespVo memberRespVo = UserLoginInterceptor.threadLocal.get();
        //获取当前秒杀商品详情
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        String json = hashOps.get(killId);
        if (StringUtils.isEmpty(json)) {
            return null;
        }
        SecKillSkuRedisTo skuRedisTo = JSON.parseObject(json, SecKillSkuRedisTo.class);
        //校验合法性
        //是否在秒杀区间
        long startTime = skuRedisTo.getStartTime();
        long endTime = skuRedisTo.getEndTime();
        long currentTime = new Date().getTime();
        if (currentTime < startTime || currentTime > endTime) {
            return null;
        }
        //校验随机码和商品id
        String randomCode = skuRedisTo.getRandomCode();
        String killIdRedis = skuRedisTo.getPromotionSessionId() + "_" + skuRedisTo.getSkuId();
        if (!randomCode.equals(key) || !killIdRedis.equals(killId)) {
            return null;
        }
        //验证购物数量是否一致
        if (num > skuRedisTo.getSeckillLimit().intValue()) {
            return null;
        }
        //验证这个人是否已经买过了，幂等性，如果秒杀成功就去占位
        //setNx
        String redisKey = memberRespVo.getId() + "_" + killIdRedis;
        //自动过期
        long ttl = endTime - currentTime;
        Boolean ifAbsent = redisTemplate.opsForValue().setIfAbsent(redisKey, num.toString(), ttl, TimeUnit.MILLISECONDS);
        if (!ifAbsent) {
            //说明已经买过了
            return null;
        }
        //校验信号量
        RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE_PREFIX + randomCode);
        try {
            boolean tryAcquire = semaphore.tryAcquire(num, 100, TimeUnit.MILLISECONDS);
            if (!tryAcquire) {
                return null;
            }
            //秒杀成功，快速下单，发送mq
            String uuid = IdWorker.getTimeId();
            SecKillOrderTo orderTo = new SecKillOrderTo();
            orderTo.setOrderSn(uuid);
            orderTo.setMemberId(memberRespVo.getId());
            orderTo.setNum(num);
            orderTo.setPromotionSessionId(skuRedisTo.getPromotionSessionId());
            orderTo.setSkuId(skuRedisTo.getSkuId());
            orderTo.setSeckillPrice(skuRedisTo.getSeckillPrice());
            rabbitTemplate.convertAndSend("order-event-exchange", "order.seckill.order", orderTo);
            long s2 = System.currentTimeMillis();
            log.info("kill 耗时：{} 豪秒", (s2 - s1));
            return uuid;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return null;
    }


    private void saveSessionInfos(List<SecKillSessionWithSkus> withSkus) {
        if (CollectionUtils.isEmpty(withSkus)) {
            return;
        }
        withSkus.stream().forEach(item -> {
            long startTime = item.getStartTime().getTime();
            long endTime = item.getEndTime().getTime();

            String key = SESSION_CACHE_PREFIX + startTime + "_" + endTime;
            List<SecKillSkuVo> skuVos = item.getRelationEntities();
            log.warn("saveSessionInfos  skuVos:{}", JSON.toJSONString(skuVos));
            if (!CollectionUtils.isEmpty(skuVos)) {
                //重复上架判断。没有相关key才操作
                Boolean hasKey = redisTemplate.hasKey(key);
                if (!hasKey) {
                    //缓存活动信息
                    List<String> strings = skuVos.stream().map(e -> {
                        return e.getPromotionSessionId() + "_" + e.getSkuId();
                    }).collect(Collectors.toList());
                    redisTemplate.opsForList().leftPushAll(key, strings);
                    log.warn("saveSessionInfos  活动信息缓存完成");
                }
            }
        });

    }

    private void saveSessionSkuInfos(List<SecKillSessionWithSkus> withSkus) {
        withSkus.stream().filter(e -> !CollectionUtils.isEmpty(e.getRelationEntities())).forEach(item -> {
            //准备hash操作
            BoundHashOperations operations = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
            item.getRelationEntities().stream().forEach(secKillSkuVo -> {
                //随机码
                String token = UUID.randomUUID().toString().replace("-", "");
                String opsKey = secKillSkuVo.getPromotionSessionId() + "_" + secKillSkuVo.getSkuId();
                if (!operations.hasKey(opsKey)) {
                    //缓存商品
                    SecKillSkuRedisTo redisTo = new SecKillSkuRedisTo();
                    //sku的基本数据
                    R skuInfo = productFeignService.getSkuInfo(secKillSkuVo.getSkuId());
                    if (skuInfo.isSuccess()) {
                        String data = JSON.toJSONString(skuInfo.get("skuInfo"));
                        SkuInfoVo skuInfoVo = JSON.parseObject(data, new TypeReference<SkuInfoVo>() {
                        });
                        redisTo.setSkuInfoVo(skuInfoVo);
                    }
                    //sku秒杀信息
                    BeanUtils.copyProperties(secKillSkuVo, redisTo);

                    //设置当前商品秒杀时间信息
                    redisTo.setStartTime(item.getStartTime().getTime());
                    redisTo.setEndTime(item.getEndTime().getTime());
                    redisTo.setRandomCode(token);
                    operations.put(opsKey, JSON.toJSONString(redisTo));
                    //如果当前场次商品库存信息已经上架就不需要上架
                    String semaphoreKey = SKU_STOCK_SEMAPHORE_PREFIX + token;
                    //使用库存做分布式信号量，限流
                    RSemaphore semaphore = redissonClient.getSemaphore(semaphoreKey);
                    //商品库存作为秒杀信号量
                    semaphore.trySetPermits(secKillSkuVo.getSeckillCount().intValue());
                }
                log.warn("saveSessionSkuInfos  活动sku信息缓存完成");

            });
        });
    }
}
